package com.qx.cn.action;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;

import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.InterceptorRef;
import org.apache.struts2.convention.annotation.InterceptorRefs;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;
import org.springframework.beans.factory.annotation.Autowired;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.qx.cn.model.ManagerWorkReport;
import com.qx.cn.model.SendDate;
import com.qx.cn.model.User;
import com.qx.cn.model.WorkReport;
import com.qx.cn.model.WorkReportItem;
import com.qx.cn.model.WorkSendGroup;
import com.qx.cn.service.ManageWorkReportService;
import com.qx.cn.service.SendEmailService;
import com.qx.cn.service.UserService;
import com.qx.cn.service.WorkReportItemService;
import com.qx.cn.service.WorkReportService;

@ParentPackage("netxzt")
@Namespace("/")
@InterceptorRefs({@InterceptorRef("content")})
@Results({
    @Result(name = "success", type = "stream", params = {"contentType", "application/vnd.ms-excel", "inputName", "excelStream", "contentDisposition", "attachment;filename=${excelFileName}.xls",
        "bufferSize", "1024"}),
    @Result(name = "outlogin", location = "/admin!loseSession"), @Result(name = "getOutlogin", location = "/admin!otherlogin"), @Result(name = "index", location = "/WEB-INF/page/user/index.jsp"),
    @Result(name = "manageworkReportForm", location = "/WEB-INF/page/manageWorkReport/manageWorkReportList.jsp")})
@Action(value = "manageWorkReport", interceptorRefs = {@InterceptorRef("loginedCheck")})
public class ManageWorkReportAction extends BaseAction
{
    /**
     * 注释内容
     */
    private static final long serialVersionUID = -2259432839589336317L;
    
    @Autowired
    private ManageWorkReportService manageWorkReportService;
    
    @Autowired
    private WorkReportService workReportService;
    
    @Autowired
    private UserService userService;
    
    @Autowired
    private WorkReportItemService workReportItemService;
    
    @Autowired
    private SendEmailService seService;
    
    private int page;
    
    private int rows;
    
    private String workReportName;
    
    private int id;
    
    private InputStream excelStream;
    
    private String excelFileName;
    
    public String manageworkReportForm()
    {
        return "manageworkReportForm";
    }
    
    /**
     * 导出excel
     * 
     * @see [类、类#方法、类#成员]
     */
    public String exportExcel()
    {
        try
        {
            ManagerWorkReport managerWorkReport = manageWorkReportService.queryById(id);
            String name = managerWorkReport.getName();
            // poi导出excel文件名乱码解决
            excelFileName = new String(name.getBytes(), "ISO-8859-1");
            String[] excelHeader = {"序号", "类型", "内容", "要求完成日期", "实际完成日期", "备注"};
            HSSFWorkbook wb = new HSSFWorkbook();
            HSSFSheet sheet = wb.createSheet(name);
            sheet.setColumnWidth(0, 7 * 256); // 第一列单元格宽度设置为7个字符宽度
            sheet.setColumnWidth(1, 12 * 256);
            sheet.setColumnWidth(2, 72 * 256);
            sheet.setColumnWidth(3, 16 * 256);
            sheet.setColumnWidth(4, 16 * 256);
            sheet.setColumnWidth(5, 32 * 256);
            
            HSSFRow row;
            HSSFCell cell;
            Font font = wb.createFont();
            font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
            
            HSSFCellStyle styleTitle = wb.createCellStyle();
            styleTitle.setFont(font);
            styleTitle.setAlignment(HSSFCellStyle.ALIGN_LEFT);
            
            HSSFCellStyle styleHead = wb.createCellStyle();
            styleHead.setFont(font);
            styleHead.setFillForegroundColor(IndexedColors.PALE_BLUE.getIndex());
            styleHead.setFillPattern(CellStyle.SOLID_FOREGROUND);
            styleHead.setAlignment(HSSFCellStyle.ALIGN_CENTER);
            styleHead.setBorderBottom(CellStyle.BORDER_THIN);
            styleHead.setBorderTop(CellStyle.BORDER_THIN);
            styleHead.setBorderLeft(CellStyle.BORDER_THIN);
            styleHead.setBorderRight(CellStyle.BORDER_THIN);
            
            HSSFCellStyle styleLeft = wb.createCellStyle();
            styleLeft.setWrapText(true);
            styleLeft.setAlignment(HSSFCellStyle.ALIGN_LEFT);
            styleLeft.setBorderBottom(CellStyle.BORDER_THIN);
            styleLeft.setBorderTop(CellStyle.BORDER_THIN);
            styleLeft.setBorderLeft(CellStyle.BORDER_THIN);
            styleLeft.setBorderRight(CellStyle.BORDER_THIN);
            styleLeft.setFillForegroundColor(IndexedColors.LEMON_CHIFFON.getIndex());
            styleLeft.setFillPattern(CellStyle.SOLID_FOREGROUND);
            
            HSSFCellStyle styleCenter = wb.createCellStyle();
            styleCenter.setAlignment(HSSFCellStyle.ALIGN_CENTER);
            styleCenter.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
            styleCenter.setBorderBottom(CellStyle.BORDER_THIN);
            styleCenter.setBorderTop(CellStyle.BORDER_THIN);
            styleCenter.setBorderLeft(CellStyle.BORDER_THIN);
            styleCenter.setBorderRight(CellStyle.BORDER_THIN);
            styleCenter.setFillForegroundColor(IndexedColors.LEMON_CHIFFON.getIndex());
            styleCenter.setFillPattern(CellStyle.SOLID_FOREGROUND);
            
            int rowNum = 1;
            String[] str = managerWorkReport.getUserIds().split(",");
            List<WorkReport> reports = new ArrayList<WorkReport>();
            for (int i = 0; i < str.length; i++)
            {
                // 2016-05-02日报-研发->2016-05-02日报
                Long userId = NumberUtils.toLong(str[i]);
                WorkReport workReport = workReportService.loadWorkReportByUserAndName(name.substring(0, 12), userId);
                if (workReport != null)
                {
                    reports.add(workReport);
                }
            }
            Collections.sort(reports);
            for (WorkReport workReport : reports)
            {
                User user = userService.loadUserById(new Long(workReport.getUserId()));
                row = sheet.createRow(rowNum++);
                cell = row.createCell(0);
                cell.setCellValue(user.getUserName());
                cell.setCellStyle(styleTitle);
                cell = row.createCell(1);
                cell.setCellValue("提交时间:" + workReport.getCreateTime());
                cell.setCellStyle(styleTitle);
                // 标题
                row = sheet.createRow(rowNum++);
                for (int j = 0; j < excelHeader.length; j++)
                {
                    cell = row.createCell(j);
                    cell.setCellValue(excelHeader[j]);
                    cell.setCellStyle(styleHead);
                }
                // 具体项目
                List<WorkReportItem> items = workReportItemService.queryWorkReportItems(workReport.getReportCode());
                for (int k = 0; k < items.size(); k++)
                {
                    WorkReportItem item = items.get(k);
                    String type = "";
                    if (item.getType() != null)
                    {
                        switch (item.getType())
                        {
                            case 1:
                                type = "本周工作";
                                break;
                            case 2:
                                type = "下周计划";
                                break;
                            case 3:
                                type = "本周小结";
                                break;
                            default:
                                break;
                        }
                    }
                    row = sheet.createRow(rowNum++);
                    cell = row.createCell(0);
                    cell.setCellValue(k + 1);
                    cell.setCellStyle(styleCenter);
                    cell = row.createCell(1);
                    cell.setCellValue(type);
                    cell.setCellStyle(styleCenter);
                    cell = row.createCell(2);
                    cell.setCellValue(item.getContent());
                    cell.setCellStyle(styleLeft);
                    cell = row.createCell(3);
                    cell.setCellValue(item.getHopeFinishDate());
                    cell.setCellStyle(styleCenter);
                    cell = row.createCell(4);
                    cell.setCellValue(item.getActualFinishDate());
                    cell.setCellStyle(styleCenter);
                    cell = row.createCell(5);
                    cell.setCellValue(item.getRemarks());
                    cell.setCellStyle(styleLeft);
                }
                rowNum++;
            }
            ByteArrayOutputStream output = new ByteArrayOutputStream();
            wb.write(output);
            byte[] ba = output.toByteArray();
            excelStream = new ByteArrayInputStream(ba);
            wb.close();
            output.flush();
            output.close();
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
        return "success";
    }
    
    /**
     * 查看汇总列表数据
     * 
     * @return
     * @see [类、类#方法、类#成员]
     */
    @SuppressWarnings({"unchecked", "rawtypes"})
    public String manageworkReportByPage()
    {
        // 更新日报汇总数据
        List<WorkSendGroup> workSendGroups = (List<WorkSendGroup>)seService.queryWorkSendGroup();
        if (!workSendGroups.isEmpty())
        {
            
            String date = DateFormatUtils.format(new Date(), "yyyy-MM-dd");
            if (seService.checkIsSendDate(date) && seService.notSend(date)) // 判断当天是否需要发日报
            {
                SendDate sysSendDate = seService.queryBySendDate(date);
                List sendTimes = seService.querySendTimes();
                if (!sendTimes.isEmpty())
                {
                    for (WorkSendGroup wGroup2 : workSendGroups)
                    {
                        if (wGroup2.getTimeTip() == 1 && StringUtils.isNotEmpty(wGroup2.getSenderIds()))
                        {
                            String[] wGroups = wGroup2.getSenderIds().split(",");
                            for (int i = 0; i < wGroups.length; i++)
                            {
                                seService.insertManageWorkReport(Integer.valueOf(wGroups[i]), wGroup2.getWorkerIds(), wGroup2.getGroupName(), sysSendDate.getType());
                            }
                        }
                    }
                }
            }
        }
        
        // 查询数据
        User user = (User)ServletActionContext.getRequest().getSession().getAttribute("user");
        ManagerWorkReport mWorkReport = new ManagerWorkReport();
        mWorkReport.setReceiverId(Integer.valueOf(user.getUserId().intValue()));
        mWorkReport.setName(workReportName);
        List results = manageWorkReportService.queryWorkReportByPage(mWorkReport, page, rows);
        JSONArray arrJson = new JSONArray();
        if (!results.isEmpty())
        {
            for (int i = 0; i < results.size(); i++)
            {
                Object[] row = (Object[])results.get(i);
                JSONObject json = new JSONObject();
                json.put("id", row[0]);
                json.put("name", row[1]);
                json.put("date", row[2]);
                json.put("receiverId", row[3]);
                json.put("userIds", row[4]);
                StringBuffer buffer = new StringBuffer();
                StringBuffer nobuffer = new StringBuffer();
                boolean isFlag = false;
                if ((row[4] != null) && (!"".equals(row[4])))
                {
                    String[] str = row[4].toString().split(",");
                    for (int j = 0; j < str.length; j++)
                    {
                        User user2 = userService.loadUserById(Long.valueOf(str[j]));
                        if (j == str.length - 1)
                        {
                            buffer.append(user2.getUserName());
                        }
                        else
                        {
                            buffer.append(user2.getUserName()).append(",");
                        }
                        
                        if (ObjectUtils.toString(row[1]).contains("日报"))
                        {
                            boolean flag = workReportService.queryCheckIsWorkReports((String)row[2], Long.valueOf(str[j]), "day");
                            if (flag)
                            {
                                nobuffer.append(user2.getUserName()).append(",");
                                isFlag = true;
                            }
                        }
                        else
                        {
                            boolean flag = workReportService.queryCheckIsWorkReports((String)row[2], Long.valueOf(str[j]), "week");
                            if (flag)
                            {
                                nobuffer.append(user2.getUserName()).append(",");
                                isFlag = true;
                            }
                        }
                    }
                    json.put("userNames", buffer.toString());
                    if (isFlag)
                    {
                        json.put("noUserNames", nobuffer.substring(0, nobuffer.length() - 1).toString());
                    }
                    else
                    {
                        json.put("noUserNames", "无");
                    }
                    json.put("userNum", Integer.valueOf(str.length));
                }
                else
                {
                    json.put("userNames", "无");
                    json.put("userNum", Integer.valueOf(0));
                    json.put("noUserNames", "无");
                }
                arrJson.add(json);
            }
        }
        
        JSONObject object = new JSONObject();
        object.put("total", Integer.valueOf(manageWorkReportService.queryAllMWorkReports(mWorkReport).size()));
        object.put("rows", arrJson);
        try
        {
            PrintWriter out = response.getWriter();
            out.print(object.toString());
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
        return null;
    }
    
    /**
     * 查看汇总详情数据
     * 
     * @return
     * @see [类、类#方法、类#成员]
     */
    public String lookManageWorkReport()
    {
        ManagerWorkReport managerWorkReport = manageWorkReportService.queryById(id);
        String name = managerWorkReport.getName();
        StringBuffer sb = new StringBuffer();
        String[] str = managerWorkReport.getUserIds().split(",");
        List<WorkReport> reports = new ArrayList<WorkReport>();
        for (int i = 0; i < str.length; i++)
        {
            // 2016-05-02日报-研发->2016-05-02日报
            Long userId = NumberUtils.toLong(str[i]);
            WorkReport workReport = workReportService.loadWorkReportByUserAndName(name.substring(0, 12), userId);
            if (workReport != null)
            {
                reports.add(workReport);
            }
        }
        Collections.sort(reports);
        for (WorkReport workReport : reports)
        {
            User user = userService.loadUserById(new Long(workReport.getUserId()));
            sb.append("<tr><td style='font-size:15px;font-weight:700'>姓名:" + user.getUserName() + "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;名称:" + workReport.getWorkReportName()
                + "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;上交时间:" + workReport.getCreateTime() + "</td></tr>");
            
            List<WorkReportItem> workReportItems = workReportItemService.queryWorkReportItems(workReport.getReportCode());
            if (name.contains("日报"))
            {
                sb.append("<tr><td colspan='4'><table border='1' cellpadding='10'>");
                sb.append(
                    "<tr style='background-color:#E8E8E8;'><th style='width:80px;'>序号</th><th style='width:500px;'>内容</th><th style='width:150px;'>时间（小时） </th><th style='width:200px;'>备注</th></tr>");
                for (int i = 0; i < workReportItems.size(); i++)
                {
                    WorkReportItem item = (WorkReportItem)workReportItems.get(i);
                    sb.append("<tr>");
                    sb.append("<td align='center'>").append(i + 1).append("</td>");
                    sb.append("<td>").append(item.getContent()).append("</td>");
                    sb.append("<td align='center'>").append(item.getWorkTime()).append("</td>");
                    sb.append("<td align='center'>").append(StringUtils.trimToEmpty(item.getRemarks())).append("</td>");
                    sb.append("</tr>");
                }
                sb.append("</td></tr></table>");
                sb.append("<tr><td>&nbsp;</td></tr>");
            }
            else if (name.contains("周报"))
            {
                sb.append("<tr><td colspan='3'><table border='1' cellpadding='10'>");
                sb.append(
                    "<tr style='background-color:#E8E8E8;'><th style='width:50px;'>序号</th><th style='width:80px;'>类型</th><th style='width:600px;'>内容</th><th style='width:150px;'>要求完成日期 </th><th style='width:150px;'>实际完成日期</th><th style='width:200px;'>备注</th></tr>");
                for (int i = 0; i < workReportItems.size(); i++)
                {
                    WorkReportItem item = (WorkReportItem)workReportItems.get(i);
                    String type = "";
                    switch (item.getType())
                    {
                        case 1:
                            type = "本周工作";
                            break;
                        case 2:
                            type = "下周计划";
                            break;
                        case 3:
                            type = "本周小结";
                            break;
                        default:
                            break;
                    }
                    sb.append("<tr>");
                    sb.append("<td align='center'>").append(i + 1).append("</td>");
                    sb.append("<td>").append(type).append("</td>");
                    sb.append("<td>").append(item.getContent()).append("</td>");
                    sb.append("<td align='center'>").append(item.getHopeFinishDate()).append("</td>");
                    sb.append("<td align='center'>").append(StringUtils.trimToEmpty(item.getActualFinishDate())).append("</td>");
                    sb.append("<td align='center'>").append(StringUtils.trimToEmpty(item.getRemarks())).append("</td>");
                    sb.append("</tr>");
                }
                sb.append("</td></tr></table>");
                sb.append("<tr><td>&nbsp;</td></tr>");
            }
        }
        
        JSONObject object = new JSONObject();
        object.put("result", 1);
        object.put("content", StringUtils.defaultIfEmpty(sb.toString(), "<br/><br/><div align='center' style='color:red;'>对不起，暂无数据!</div>"));
        try
        {
            PrintWriter out = response.getWriter();
            out.print(object.toString());
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
        return null;
    }
    
    public ManageWorkReportService getManageWorkReportService()
    {
        return this.manageWorkReportService;
    }
    
    public void setManageWorkReportService(ManageWorkReportService manageWorkReportService)
    {
        this.manageWorkReportService = manageWorkReportService;
    }
    
    public int getPage()
    {
        return this.page;
    }
    
    public void setPage(int page)
    {
        this.page = page;
    }
    
    public int getRows()
    {
        return this.rows;
    }
    
    public void setRows(int rows)
    {
        this.rows = rows;
    }
    
    public String getWorkReportName()
    {
        return workReportName;
    }
    
    public void setWorkReportName(String workReportName)
    {
        this.workReportName = workReportName;
    }
    
    public int getId()
    {
        return id;
    }
    
    public void setId(int id)
    {
        this.id = id;
    }
    
    public InputStream getExcelStream()
    {
        return excelStream;
    }
    
    public void setExcelStream(InputStream excelStream)
    {
        this.excelStream = excelStream;
    }
    
    public String getExcelFileName()
    {
        return excelFileName;
    }
    
    public void setExcelFileName(String excelFileName)
    {
        this.excelFileName = excelFileName;
    }
    
}